package com.shujiaotong.interceptor;

import com.alibaba.fastjson.JSON;

import com.shujiaotong.common.BaseContext;
import com.shujiaotong.common.PathMatcher;
import com.shujiaotong.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component //注意当前类必须受Spring容器控制
//定义拦截器类，实现HandlerInterceptor接口
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 静态、白名单资源放行
        String requestURI = request.getRequestURI();// 访问路径
        boolean check = PathMatcher.check(requestURI);
        if(check){
            log.info("白名单放行：{}",requestURI);
            return true;
        }

        //2. 登录了 放行
//    HttpSession session = request.getSession();
//    Object user = session.getAttribute("user");
        // 2.1 从请求头获取auth
        String auth = request.getHeader("auth");
        Object userId= null;
        if(!StringUtils.isEmpty(auth)){
            userId = redisTemplate.opsForValue().get("auth" + auth);
        }
        if(!StringUtils.isEmpty(userId)){
            log.info("已登录放行：{}",requestURI);
            // 把用户ID存入线程空间
            BaseContext.setCurrentId((Long) userId);
//      System.err.println("interceptor"+Thread.currentThread().getName());
            return true;
        }

        //3. 未登录拦截
        response.setStatus(401);// 响应状态码
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}